package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * Created by 30821 on 2018/7/11.
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService{
    @Autowired
    private EmployeeMapper mapper;

    @Override
    public void save(Employee entity) {
        mapper.insert(entity);
        List<Role> roles = entity.getRoles();
        if (roles!=null) {
            for (Role role : roles) {
                mapper.insertRelation(entity.getId(), role.getId());
            }
        }
    }

    @Override
    public void delete(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Employee entity) {
        mapper.deleteRelation(entity.getId());
        mapper.updateByPrimaryKey(entity);
        List<Role> roles = entity.getRoles();
        if (roles!=null) {
            for (Role role : roles) {
                mapper.insertRelation(entity.getId(), role.getId());
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id
        );
    }

    @Override
    public List<Employee> list() {
        return mapper.selectAll();
    }

    @Override
    public PageResult query(EmployeeQueryObject qo) {
        int total = mapper.queryForCount(qo);
        if(total==0){
            return new PageResult();
        }
        List<Employee> rows = mapper.queryForList(qo);
        return new PageResult(total,rows);
    }

    @Override
    public void changeState(Long id) {
        mapper.changeState(id);
    }

    @Override
    public Employee checkName(String username) {
        return mapper.checkName(username);
    }


    public Set<String> getRoleByEmpId(Long id) {
        return mapper.getRoleByEmpId(id);
    }

    public Set<String> getPermissionByEmpId(Long id) {
        return mapper.getPermissionByEmpId(id);
    }

    public Employee getByUsername(String username) {
        return mapper.getByUsername(username);
    }
}
